import React from "react";
import {
  BrowserRouter,
  useLocation,
  useRoutes,
  Navigate,
} from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "../store";

const MainLayout = React.lazy(() => import("../views/mainLayout"));
const Home = React.lazy(() => import("../views/home"));
const Car = React.lazy(() => import("../views/car"));
const Detail = React.lazy(() => import("../views/detail"));
const Login = React.lazy(() => import("../views/login"));

const PrivateRoute = ({ children }: { children: JSX.Element }) => {
  const isLogin = useSelector((state: RootState) => state.user.isLogin);
  const location = useLocation();
  const pathname = location.pathname;
  if (isLogin) {
    // 已经登录
    if (pathname === "/login") {
      // 已经登录 但是访问登录页面
      return <Navigate to="/"></Navigate>;
    } else {
      // 已经登录 但是访问非登录页面
      return children;
    }
  } else {
    // 未登录
    if (pathname === "/login") {
      return children;
    } else {
      return <Navigate to="/login"></Navigate>;
    }
  }
};

const routes = [
  {
    path: "/",
    element: (
      <PrivateRoute>
        <MainLayout>
          <Home></Home>
        </MainLayout>
      </PrivateRoute>
    ),
  },
  {
    path: "/car",
    element: (
      <PrivateRoute>
        <MainLayout>
          <Car></Car>
        </MainLayout>
      </PrivateRoute>
    ),
  },
  {
    path: "/detail/:id",
    element: (
      <PrivateRoute>
        <Detail></Detail>
      </PrivateRoute>
    ),
  },
  {
    path: "/login",
    element: (
      <PrivateRoute>
        <Login></Login>
      </PrivateRoute>
    ),
  },
];

const Router = () => {
  const App = () => useRoutes(routes);
  return (
    <BrowserRouter>
      <App></App>
    </BrowserRouter>
  );
};

export default Router;
